//
//  LCZLastColumnController.m
//  PersonalNews
//
//  Created by dllo on 15/12/2.
//  Copyright © 2015年 changshuhua. All rights reserved.
//

#import "LCZLastColumnController.h"
#import "ReadRecommendDetail.h"
#import "ImgInformation.h"
#import "LCZLastColumnModel.h"
#import "LCZFMDatabase.h"



#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height


@interface LCZLastColumnController ()<UIWebViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong)UIWebView *lastWebView;
@property (nonatomic, strong)LCZBaseImageView *headImageView;
@property (nonatomic, copy)NSString *bodyStr;

@property (nonatomic, copy)NSString *strURL;

@property (nonatomic, strong)NSMutableArray *detailArr;
@property (nonatomic, strong)NSMutableArray *picArr;

@property (nonatomic, copy)NSString *titleStr;
@property (nonatomic, copy)NSString *sourseStr;
@property (nonatomic, copy)NSString *timeStr;
// 收藏按钮
@property (nonatomic, strong)UIButton *saveButton;

@end

@implementation LCZLastColumnController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.detailArr = [NSMutableArray array];
    self.picArr = [NSMutableArray array];
    
    self.strURL = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", self.docid];
    
    // 上面有个栏
    self.headImageView = [[LCZBaseImageView alloc]init];
    self.headImageView.frame = CGRectMake(0, 0, WIDTH, 64);
    [self.view addSubview:self.headImageView];
    self.headImageView.image = [UIImage imageNamed:@"column1.png"];
    
    // 最上面的返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(10, 25, 30, 30);
    backButton.layer.cornerRadius = 15;
    
    backButton.backgroundColor = [UIColor colorWithRed:0.45 green:0.46 blue:0.46 alpha:1];
    [self.view addSubview:backButton];
    [backButton setImage:[UIImage imageNamed:@"left.png"] forState:UIControlStateNormal];
    [backButton setTintColor:[UIColor whiteColor]];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    // 一个收藏按钮
    self.saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.saveButton.frame = CGRectMake(WIDTH - 30 - 10, 25, 30, 30);
    [self.view addSubview:self.saveButton];
    
    
    // 加载webView的数据
    NSLog(@"---------%@", self.docid);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.docid]];
    
    [self.lastWebView loadRequest:request];

    // 请求数据
    [self createData];
    
}

// 加载数据
- (void)createData
{
    [LCZNetWorkTools getdataWithString: self.strURL block:^(id block) {
        self.bodyStr = block[self.docid][@"body"];
        self.titleStr = block[self.docid][@"title"];
        self.sourseStr = block[self.docid][@"source"];
        self.timeStr = block[self.docid][@"ptime"];
        
        //判断是否收藏过
        [[LCZFMDatabase shareFMDatabase] openDB:2];
       
        if ([[LCZFMDatabase shareFMDatabase]selectAllByLCZColumnModelTitle:self.titleStr]) {
            [self.saveButton setImage:[UIImage imageNamed:@"xin2.png"] forState:UIControlStateNormal];
            [self.saveButton addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [self.saveButton setImage:[UIImage imageNamed:@"xin1.png"] forState:UIControlStateNormal];
            [self.saveButton addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
        }

        
        ReadRecommendDetail *readDetail = [[ReadRecommendDetail alloc] init];
        [readDetail setValuesForKeysWithDictionary:[block objectForKey:self.docid]];
        [self.detailArr addObject:readDetail];

        for (NSDictionary *temp in [[block objectForKey:self.docid]objectForKey:@"img"] ) {
            ImgInformation *image =  [[ImgInformation alloc] init];
            [image setValuesForKeysWithDictionary:temp];
            [_picArr addObject:image];
        }
        
        [self createWebView];
    }];
    
   
}
// 创建webView
- (void)createWebView
{
    self.lastWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64)];
    [self.view addSubview:self.lastWebView];
    // 设置代理人
    self.lastWebView.delegate = self;
    self.lastWebView.scalesPageToFit = self;
    self.lastWebView.scrollView.bounces = NO;
    
    // 拼接标题
    NSString *head = [NSString stringWithFormat:@"<p><font size = 50>%@</p><p><font size = 7><font color=#7F7F7F>%@   <font color = #7171C6> %@</p><font color = #080808>", self.titleStr, self.timeStr, self.sourseStr];
    _bodyStr = [head stringByAppendingString:_bodyStr];

    // Range is: {第几个元素出现<p>, <p>的长度}
    NSRange range = [_bodyStr rangeOfString:@"<p>"];
    _bodyStr = [_bodyStr stringByReplacingCharactersInRange:range withString:@"<p><font size = 7>"];
    for (ImgInformation * image in _picArr) {
        NSRange range1 = [_bodyStr rangeOfString:image.ref];
        if (image.pixel != nil) {
            
            NSArray *arr = [image.pixel componentsSeparatedByString:@"*"];
            CGFloat h = [arr[1] floatValue];
            CGFloat w = [arr[0] floatValue];
            
            // 960是webview固定的
            NSString *width = [NSString stringWithFormat:@"960 - 20"];
            NSString *height = [NSString stringWithFormat:@"%g", h / w * (960 - 20)];
            _bodyStr = [_bodyStr stringByReplacingCharactersInRange:range1 withString:[NSString stringWithFormat:@"<p><font size = 8> <br><img src=%@ width=%@ height=%@ ><br>", image.src, width , height]];
        }
    }
    [self.lastWebView loadHTMLString:_bodyStr baseURL:nil];

}

- (void)viewWillAppear:(BOOL)animated
{
//    self.lastWebView.scrollView.contentOffset = CGPointMake(0, 64);
    NSLog(@"%f", self.lastWebView.scrollView.contentOffset.y);
}

// 返回按钮的实现方法
- (void)backAction:(UIButton *)button
{
    // 模态回去 没有NavigationController 让self跳转
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// 收藏按钮实现方法
- (void)saveAction:(UIButton *)button
{
    
    // 如果收藏按钮是空心的
    if ([self.saveButton.imageView.image isEqual:[UIImage imageNamed:@"xin1.png"]]) {
        [self.saveButton setImage:[UIImage imageNamed:@"xin2.png"] forState:UIControlStateNormal];
        
        [[LCZFMDatabase shareFMDatabase] openDB:2];
        NSLog(@"%@", NSHomeDirectory());
        
        LCZLastColumnModel *lastModel = [[LCZLastColumnModel alloc]init];
        lastModel.title = self.titleStr;
        lastModel.url = self.strURL;
        
        [[LCZFMDatabase shareFMDatabase] openDB:2];
        [[LCZFMDatabase shareFMDatabase] insertData:lastModel :2];
    } else {
        [self.saveButton setImage:[UIImage imageNamed:@"xin1.png"] forState:UIControlStateNormal];
        
        LCZLastColumnModel *lastModel = [[LCZLastColumnModel alloc]init];
        lastModel.title = self.titleStr;
        lastModel.url = self.strURL;
        
        [[LCZFMDatabase shareFMDatabase] openDB:2];
        [[LCZFMDatabase shareFMDatabase] clearAll:lastModel];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
